package com.cs342.uwosh.cloudycontacts.tasks.network;

import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;

import com.cs342.uwosh.cloudycontacts.LoginActivity;
import com.cs342.uwosh.cloudycontacts.MainActivity;
import com.cs342.uwosh.cloudycontacts.RestClient;

import android.graphics.Typeface;
import android.os.AsyncTask;
import android.util.Log;

public class AuthenticateCredentialsTask  extends AsyncTask<String, String, Boolean>
{
	public int iLanguage = 0;
	Typeface arabicFont = null;
	int TIMEOUT_MILLISEC = 10000; // = 10 seconds
	
	@Override
	protected Boolean doInBackground(String... params)
	{
		try
		{
			JSONObject json = new JSONObject();
			json.put("user_name", params[0]);
			json.put("password", params[1]);
			
			HttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams,TIMEOUT_MILLISEC);
			HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
			HttpClient client = new DefaultHttpClient(httpParams);
			
			String url = "http://softeng.cs.uwosh.edu/students/kiserj66/Web/login.php";
			
			HttpPost request = new HttpPost(url);
			request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
			request.setHeader("json", json.toString());
			HttpResponse response = client.execute(request);
			HttpEntity entity = response.getEntity();
			if (entity != null)
			{
				InputStream instream = entity.getContent();
				
				String result = RestClient.convertStreamToString(instream);
				Log.i("Read from server", result);
				System.out.println("hihihi"+result+"byebyebye");
				result = result.replaceAll("\\n", "");
				System.out.println("hihihi"+result+"byebyebye");
				MainActivity.CURRENT_USER = Integer.parseInt(result);
				return true;
			}
			return false;
		}
		catch (Throwable t)
		{
			return false;
		}
	}
	
	@Override
	protected void onPostExecute(Boolean result)
	{
		LoginActivity.PASS_FAIL = result;
	}
}
